package com.zone.lib.download.install;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.util.Log;

import androidx.core.content.FileProvider;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;

/**
 * @Author: pkqlqx
 * @CreateDate: 2022/1/5 19:33
 * @Description:
 */
public class ApkController {

    /**
     * 描述: 安装
     */
    public static boolean install(String apkPath, Context context) {
        // 先判断手机是否有root权限
        if (hasRootPermission()) {
            // 有root权限，利用静默安装实现
            return installSilent(apkPath);
        } else {
            // 没有root权限，利用意图进行安装
            File file = new File(apkPath);
            if (!file.exists()) {
                return false;
            }
            Intent intent = new Intent(Intent.ACTION_VIEW);
            Uri uri;
            String type = "application/vnd.android.package-archive";
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
                uri = Uri.fromFile(file);
            } else {
                String authority = context.getPackageName() + ".FileProvider";
                uri = FileProvider.getUriForFile(context, authority, file);
                intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            }
            context.grantUriPermission(
                    context.getPackageName(),
                    uri,
                    Intent.FLAG_GRANT_READ_URI_PERMISSION
            );
            intent.setDataAndType(uri, type);
            //intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            context.startActivity(intent);
            return true;
        }
    }

    /**
     * 描述: 卸载
     */
    boolean uninstall(String packageName, Context context) {
        if (hasRootPermission()) {
            // 有root权限，利用静默卸载实现
            return silentUninstall(packageName);
        } else {
            Uri packageURI = Uri.parse("package:$packageName");
            Intent uninstallIntent = new Intent(Intent.ACTION_DELETE, packageURI);
            uninstallIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(uninstallIntent);
            return true;
        }
    }

    /**
     * 判断手机是否有root权限
     */
    public static boolean hasRootPermission() {
        PrintWriter printWriter;
        Process process = null;
        try {
            process = Runtime.getRuntime().exec("su");
            if (process != null){
                printWriter = new PrintWriter(process.getOutputStream());
                printWriter.flush();
                printWriter.close();
                int value = process.waitFor();
                return returnResult(value);
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (process != null){
                process.destroy();
            }
        }
        return false;
    }


    /**
     * 静默安装 利用 Runtime.getRuntime().exec()
     * @param apkPath
     * @return boolean true -- 安装成功，false -- 安装失败
     */
    private static boolean installSilent(String apkPath) {
        boolean result = false;
        DataOutputStream dataOutputStream = null;
        BufferedReader errorStream = null;
        try {
            // 申请su权限
            Process process = Runtime.getRuntime().exec("su");
            dataOutputStream = new DataOutputStream(process.getOutputStream());
            // 执行pm install命令
            String command = "pm install -r $apkPath\n";
            dataOutputStream.write(command.getBytes(StandardCharsets.UTF_8));
            dataOutputStream.writeBytes("exit\n");
            dataOutputStream.flush();
            process.waitFor();
            errorStream = new BufferedReader(new InputStreamReader(process.getErrorStream()));
            StringBuilder msg = new StringBuilder();
            String line;
            // 读取命令的执行结果
            do {
                line = errorStream.readLine();
                if (line != null) {
                    msg.append(line);
                } else {
                    break;
                }
            } while (true);
            Log.d("TAG", "install msg is "+msg);
            // 如果执行结果中包含 Failure 或者 denied 字样就认为是安装失败，否则就认为安装成功
            if (!msg.toString().contains("Failure") && !msg.toString().contains("denied")) {
                result = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (dataOutputStream != null){
                    dataOutputStream.close();
                }
                if (errorStream != null){
                    errorStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        Log.d("TAG", "install result is: "+result);
        return result;
    }

    /**
     * 静默卸载
     */
    private boolean silentUninstall(String packageName) {
        PrintWriter printWriter;
        Process process = null;
        try {
            process = Runtime.getRuntime().exec("su");
            if (process != null){
                printWriter = new PrintWriter(process.getOutputStream());
                printWriter.println("LD_LIBRARY_PATH=/vendor/lib:/system/lib ");
                printWriter.println("pm uninstall $packageName");
                printWriter.flush();
                printWriter.close();
                int value = process.waitFor();
                return returnResult(value);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (process != null) {
                process.destroy();
            }
        }
        return false;
    }

    /**
     * 启动 app
     * com.exmaple.client/.MainActivity
     * com.exmaple.client/com.exmaple.client.MainActivity
     */
    Boolean startApp(String packageName, String activityName) {
        String cmd = "am start -n $packageName/$activityName \n";
        Process process = null;
        try {
            process = Runtime.getRuntime().exec(cmd);
            int value = process.waitFor();
            return returnResult(value);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (process != null) {
                process.destroy();
            }
        }
        return false;
    }

    private static Boolean returnResult(int value)  {
        // 代表成功 0成功 1 失败
        return value == 0;
    }
}
